package com.itheima.service.Impl;

import com.alibaba.dubbo.config.annotation.Service;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.itheima.POJO.Member;
import com.itheima.POJO.Order;
import com.itheima.POJO.OrderSetting;
import com.itheima.constant.MessageConstant;
import com.itheima.dao.memberMapper;
import com.itheima.dao.orderMapper;
import com.itheima.dao.ordersettingMapper;
import com.itheima.entity.PageResult;
import com.itheima.entity.Result;
import com.itheima.service.orderService;
import com.itheima.utils.DateUtils;
import com.itheima.utils.SMSUtils;
import org.apache.ibatis.annotations.Insert;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;

@Service(interfaceClass = orderService.class)
@Transactional
public class orderServiceImpl implements orderService {
    @Autowired
    private orderMapper orderMapper;
    @Autowired
    private ordersettingMapper ordersettingMapper;
    @Autowired
    private memberMapper memberMapper;

    //分页查询体检预约信息
    @Override
    public PageResult pageQuery(Integer currentPage, Integer pageSize, String queryString) throws Exception {
        PageHelper.startPage(currentPage,pageSize);
        Page<Map> page = orderMapper.pageQuery(queryString);
        long total = page.getTotal();
        List<Map> result = page.getResult();
        //日期格式处理
        for (Map map : result) {
            Date orderDate = (Date) map.get("orderDate");
            map.put("orderDate",DateUtils.parseDate2String(orderDate));
        }

        return new PageResult(total,result);

    }

    //取消预约(删除预约信息)
    @Override
    public void deleteOrderById(Integer id) {
        //删除预约信息
        orderMapper.deleteOrderById(id);
    }

    //新增体检预约信息
    @Override
    public Result addOrderAndMember(Map map, Integer[] checkgroupIds) throws Exception {
        Date orderDate = DateUtils.parseString2Date((String) map.get("orderDate"));
        //判断预约日期是否开启预约
        OrderSetting orderSetting = ordersettingMapper.selectOrderSettingByOrderDate(orderDate);
        if(orderSetting == null) {
            //未开启预约
            return new Result(false,MessageConstant.SELECTED_DATE_CANNOT_ORDER);
        }
        //判断预约日期是否已预约满
        if(orderSetting.getReservations()+checkgroupIds.length > orderSetting.getNumber()) {
            //预约已满
            return new Result(false,MessageConstant.ORDER_FULL);
        }
        //判断用户是否是会员
        String telephone = (String) map.get("telephone");
        Member member = memberMapper.findMemberBYtelephone(telephone);
        if(member != null) {
            //是会员,判断是否重复预约
            Order order = new Order();
            order.setOrderDate(orderDate);
            for (Integer checkgroupId : checkgroupIds) {
                order.setSetmealId(checkgroupId);
                List<Order> orders = orderMapper.findByCondition(order);
                if(!(orders != null && orders.size() > 0)) {
                    //预约重复
                    return new Result(false,MessageConstant.HAS_ORDERED);
                }
            }
        }else{
            //不是会员,注册会员
            member = new Member();
            member.setName((String)map.get("name"));
            member.setBirthday(DateUtils.parseString2Date((String)map.get("birthday")));
            member.setIdCard((String) map.get("idCard"));
            member.setAge(Integer.parseInt((String)map.get("age")));
            member.setMarriage((String) map.get("marriage"));
            member.setPhoneNumber(telephone);
            member.setSex((String) map.get("sex"));
            orderMapper.addMember(member);
        }
        //新增预约体检信息
        Integer memberId = member.getId();
        Order order = new Order();
        order.setOrderDate(orderDate);
        order.setOrderType((String) map.get("orderType"));
        order.setOrderStatus(Order.ORDERSTATUS_NO);
        order.setMemberId(memberId);
        for (Integer checkgroupId : checkgroupIds) {
            order.setSetmealId(checkgroupId);
            //添加预约信息
            orderMapper.addOrder(order);
            orderSetting.setReservations(orderSetting.getReservations() +1);
            ordersettingMapper.updateOrderSetting(orderSetting);
        }
        return new Result(true,MessageConstant.ORDER_SUCCESS);
    }


    @Override
    public Result submitOrder(Map map) throws Exception {
        //    {"setmealId":"12","sex":"1","telephone":"15385692072","name":"费雪皓",
        //     "idCard":"340521199706102817","validateCode":"98ff71","orderDate":"2019-12-30"}

        String name = (String) map.get("name");
        //1.先根据时间查看这一天可以不可以预约
        String orderDate = (String) map.get("orderDate");
        Date date = DateUtils.parseString2Date(orderDate);
        int setmealId =  Integer.parseInt((String) map.get("setmealId"));
        String telephone = (String) map.get("telephone");


        OrderSetting orderSetting= orderMapper.findOrdersettingByorderDate(orderDate);
      if (orderSetting ==null || orderSetting.equals("")){
          //所选日期不可进行预约
          return new Result(false,MessageConstant.SELECTED_DATE_CANNOT_ORDER);
      }
        //2.检查这一天是否 已经预约满
      if (orderSetting.getNumber()-orderSetting.getReservations()<=0){
          //该日期预约已满
          return new Result(false, MessageConstant.ORDER_FULL);
      }
        // 3. 检查该用户是否在这天已经预约过了 ,如果预约过了那就不可以重复预约
      Member orderMember =orderMapper.findMemberByName(name);
        Integer memberId =null;
        //要查第三点先查该用户是否为会员
        //该用户是会员
      if (orderMember!=null){
          //3.1 该用户是会员可能已经进行过预约
          memberId= orderMember.getId();
          //当天不能预约同样的
         Order member_order= orderMapper.findBymemberIDANDorderDate(memberId,orderDate,setmealId);
         if (member_order!=null){
             //重复预约了
             return new Result(false,MessageConstant.HAS_ORDERED);
         }
      }
      //该用户不是会员
        //不是会员的话 肯定没有预约过
      if (orderMember ==null) {
          //4  不是会员需要 先添加其为会员,并且需要返回这个新添加的会员id
          /*
          private Integer id;//主键
    private String fileNumber;//档案号
    private String name;//姓名
    private String sex;//性别
    private String idCard;//身份证号
    private String phoneNumber;//手机号
    private Date regTime;//注册时间
    private String password;//登录密码
    private String email;//邮箱
    private Date birthday;//出生日期
    private String remark;//备注
           */
          //4.1新增会员
          //设置该会员现在所能设置的信息
          Member member = new Member();
          member.setName((String) map.get("name"));
          member.setPhoneNumber((String) map.get("telephone"));
          member.setIdCard((String) map.get("idCard"));
          member.setSex((String) map.get("sex"));
          member.setRegTime(new Date());
          //将该会员添加到会员表 并且返回主键
          orderMapper.addMember(member);
          //添加到会员表以后就可以预约了
          memberId = member.getId();
      }

          //5 可以预约
             /*
             public static final String ORDERTYPE_TELEPHONE = "电话预约";
             public static final String ORDERTYPE_WEIXIN = "微信预约";
             public static final String ORDERSTATUS_YES = "已到诊";
             public static final String ORDERSTATUS_NO = "未到诊";
             private Integer id;
             private Integer memberId;//会员id
             private Date orderDate;//预约日期
             private String orderType;//预约类型 电话预约/微信预约
             private String orderStatus;//预约状态（是否到诊）
              private Integer setmealId;//体检套餐id
             */

          Order order = new Order(memberId,date,Order.ORDERTYPE_WEIXIN,Order.ORDERSTATUS_NO,setmealId);
          orderMapper.addOrder(order);
          //5.1.预约成功 以后需要将ordersetting表中的已预约人数加1
          orderSetting.setReservations(orderSetting.getReservations()+1);
          orderMapper.editReservations(orderSetting);
          //5.2 .预约成功以后发送预约成功信息给用户
          SMSUtils.sendShortMessage("SMS_179215160",telephone,(String)map.get("orderDate"));
          return new Result(true,MessageConstant.ORDER_SUCCESS,order.getId());
      }

    @Override
    public Map<String, String> findinfoByID(Integer id) throws Exception {
         /*
         <p>体检人：{{orderInfo.member}}</p>
          <p>体检套餐：{{orderInfo.setmeal}}</p>
          <p>体检日期：{{orderInfo.orderDate}}</p>
         <p>预约类型：{{orderInfo.orderType}}</p>
         */



      Order order=  orderMapper.findorderByID(id);

        String memberName   = orderMapper.findMemberBYid(order.getMemberId());
        Map<String, String> map = new HashMap<>();
        Integer setmealId = order.getSetmealId();
        String stemealname=   orderMapper.findSetmealByID(setmealId);

        Date date = order.getOrderDate();
        String oederDate = DateUtils.parseDate2String(date);

        String orderType = order.getOrderType();

        map.put("member",memberName);
        map.put("setmeal",stemealname);
        map.put("orderDate",oederDate);
        map.put("orderType",orderType);
        return map;
    }

    @Override
    public List<Integer> findOrderCountByMouth(List<String> arrayList) {
        List<Integer> counts = new ArrayList<>();
        for (String dataString : arrayList) {
            String replace = dataString.replace(".", "-");
            Integer count = orderMapper.findMemberCountByMouth(replace);
            counts.add(count);
        }

        return counts;
    }
}
